package com.bishe.psy.service.impl;

import com.bishe.psy.common.AppResult;
import com.bishe.psy.common.ResultCode;
import com.bishe.psy.dao.SleepMapper;
import com.bishe.psy.exception.ApplicationException;
import com.bishe.psy.model.Sleep;
import com.bishe.psy.service.ISleepService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * Created with Intellij IDEA.
 * Description:
 * User: L
 * Date: 2024-04-26
 * Time: 17:40
 */

@Slf4j
@Service
public class SleepServiceImpl implements ISleepService {

    @Resource
    private SleepMapper sleepMapper;


    @Override
    public void create(Sleep sleep) {

        //1.参数校验
        if(sleep == null || sleep.getUserId() == null || sleep.getUserId() <= 0
        || sleep.getQuality() == null || sleep.getQuality() < 0
        || sleep.getAsleep() == null || sleep.getAsleep() < 0
        || sleep.getSleepTime() == null || sleep.getSleepTime() < 0
        || sleep.getSleepEfficiency() == null || sleep.getSleepEfficiency() < 0
        || sleep.getSleepDisturbances() == null || sleep.getSleepDisturbances() < 0
        || sleep.getHypnoticDrugs() == null || sleep.getHypnoticDrugs() < 0
        || sleep.getDysfunction() == null || sleep.getDysfunction() < 0
        || sleep.getScore() == null || sleep.getScore() < 0){
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2.设置默认值
        sleep.setDeleteState((byte) 0);
        Date date = new Date();
        sleep.setCreateState(date);
        sleep.setUpdateState(date);

        //3.调用数据库
        int row = sleepMapper.insertSelective(sleep);

        //4.判断是否插入成功
        if(row <= 0 ) {
            log.warn("sleep测试问卷插入" + ResultCode.FAILED);
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

    @Override
    public Sleep selectByIdNewResult(Long userId) {

        //1.参数校验
        if(userId == null || userId <= 0) {
            log.warn("传入id为空");
            throw new ApplicationException(AppResult.failed("传入参数为空"));
        }

        //2.根据用户id查询最新睡眠测试结果
        Sleep sleep = sleepMapper.selectByIdNewResult(userId);

        //3.返回结果
        return sleep;

    }

    @Override
    public List<Sleep> selectByUserId(Long userId) {

        //1.参数校验
        if(userId == null || userId <= 0) {
            log.warn("传入id为空");
            throw new ApplicationException(AppResult.failed("传入参数为空"));
        }

        //2.调用数据库
        List<Sleep> sleeps = sleepMapper.selectByUserId(userId);

        //3.返回结果
        return sleeps;

    }
}
